package com.mytools.thirparty.jenkins.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.mytools.thirparty.jenkins.config.JenkinsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/jenkins")
@Slf4j
public class JenkinsController {

    @Autowired
    private JenkinsConfig jenkinsConfig;
    @RequestMapping("/build")
    public String build(@RequestBody List<String> jobNameList) {
        StringBuilder result = new StringBuilder();
        
        for (String jobName : jobNameList) {
            String url = String.format("%s/job/%s/build",
                    jenkinsConfig.getUrl(), jobName);

            // 创建Basic认证
            String auth = jenkinsConfig.getUsername() + ":" + jenkinsConfig.getToken();
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());

            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Basic " + encodedAuth);

            try {
                // 发送POST请求
                HttpUtil.createRequest(Method.POST, url)
                        .addHeaders(headers)
                        .execute()
                        .body();

                log.info("成功触发Jenkins构建: {}", jobName);
                result.append(jobName).append(": 成功\n");
            } catch (Exception e) {
                log.error("触发Jenkins构建失败: {}", jobName, e);
                result.append(jobName).append(": 失败\n");
            }
        }
        
        return result.toString();
    }
}